﻿BUYER_LEVEL_PIC = [
    '',
    'http://pics.taobaocdn.com/newrank/b_red_1.gif',
    'http://pics.taobaocdn.com/newrank/b_red_2.gif',
    'http://pics.taobaocdn.com/newrank/b_red_3.gif',
    'http://pics.taobaocdn.com/newrank/b_red_4.gif',
    'http://pics.taobaocdn.com/newrank/b_red_5.gif',
    'http://pics.taobaocdn.com/newrank/b_blue_1.gif',
    'http://pics.taobaocdn.com/newrank/b_blue_2.gif',
    'http://pics.taobaocdn.com/newrank/b_blue_3.gif',
    'http://pics.taobaocdn.com/newrank/b_blue_4.gif',
    'http://pics.taobaocdn.com/newrank/b_blue_5.gif',
    'http://pics.taobaocdn.com/newrank/b_cap_1.gif',
    'http://pics.taobaocdn.com/newrank/b_cap_2.gif',
    'http://pics.taobaocdn.com/newrank/b_cap_3.gif',
    'http://pics.taobaocdn.com/newrank/b_cap_4.gif',
    'http://pics.taobaocdn.com/newrank/b_cap_5.gif',
    'http://pics.taobaocdn.com/newrank/b_crown_1.gif',
    'http://pics.taobaocdn.com/newrank/b_crown_2.gif',
    'http://pics.taobaocdn.com/newrank/b_crown_3.gif',
    'http://pics.taobaocdn.com/newrank/b_crown_4.gif',
    'http://pics.taobaocdn.com/newrank/b_crown_5.gif'
];
SELLER_LEVEL_PIC = [
    '',
    'http://pics.taobaocdn.com/newrank/s_red_1.gif',
    'http://pics.taobaocdn.com/newrank/s_red_2.gif',
    'http://pics.taobaocdn.com/newrank/s_red_3.gif',
    'http://pics.taobaocdn.com/newrank/s_red_4.gif',
    'http://pics.taobaocdn.com/newrank/s_red_5.gif',
    'http://pics.taobaocdn.com/newrank/s_blue_1.gif',
    'http://pics.taobaocdn.com/newrank/s_blue_2.gif',
    'http://pics.taobaocdn.com/newrank/s_blue_3.gif',
    'http://pics.taobaocdn.com/newrank/s_blue_4.gif',
    'http://pics.taobaocdn.com/newrank/s_blue_5.gif',
    'http://pics.taobaocdn.com/newrank/s_cap_1.gif',
    'http://pics.taobaocdn.com/newrank/s_cap_2.gif',
    'http://pics.taobaocdn.com/newrank/s_cap_3.gif',
    'http://pics.taobaocdn.com/newrank/s_cap_4.gif',
    'http://pics.taobaocdn.com/newrank/s_cap_5.gif',
    'http://pics.taobaocdn.com/newrank/s_crown_1.gif',
    'http://pics.taobaocdn.com/newrank/s_crown_2.gif',
    'http://pics.taobaocdn.com/newrank/s_crown_3.gif',
    'http://pics.taobaocdn.com/newrank/s_crown_4.gif',
    'http://pics.taobaocdn.com/newrank/s_crown_5.gif',
];

ITEM_DETAIL_URL_PREFIX = 'http://item.taobao.com/auction/item_detail-db2-';

current_display_ce_detail = null;

function show_tipwindow(s) {
    $('#tipwindow span').html(s);
    $('#tipwindow').css({'display':'block'});
}

function hide_tipwindow() {
    //$('#tipwindow').css({'display':'none'});
    $('#tipwindow').hide(300);
}

function show_tiperrwindow(s) {
    $('#tiperrwindow span').html(s);
    $('#tiperrwindow').css({'display':'block'});
    $('#tiperrwindow').fadeTo(4000, 1, function() {
        $('#tiperrwindow').hide(300);
    });
}

function title_toggle(title_id, div_id) {
    if ('block' == $('#'+div_id).css('display')) {
        $('#'+title_id).removeClass('opentriangle');
        $('#'+div_id).css({'display':'none'});
    } else {
        $('#'+title_id).addClass('opentriangle');
        $('#'+div_id).css({'display':'block'});
    }
}

function delete_subscription(nick) {
    if(window.confirm('确定要取消订阅'+nick+'?')) {
        show_tipwindow('Loading...');
        $.ajax({
            url: '/favshop/unsubscribe',
            type: 'POST',
            data: {'nick': nick, 'favshopuser':$('#subscription_user').val()},
            error: function(xhr, textStatus) {
                hide_tipwindow();
                show_tiperrwindow('Oops, there are something wrong when server process your request...');
            },
            success: function(data, textStatus) {
                hide_tipwindow();
                console.log(data);
                if('ERROR' == data) {
                    show_tiperrwindow('Oops, there are something wrong when server process your request...');
                } else if('REFRESH' == data) {
                    load_subscription_side_bar($('#subscription_user').val());
                }
            }
        });
    }
}

function generate_shop_info(obj) {  
    svr_obj = obj;
    html_str = '';
    if(svr_obj != null) {
        // generate title1
        html_str = '<h3><a id="title1" href="javascript:title_toggle(\'title1\', \'title1_content\')" class="toggled-section opentriangle">'+svr_obj['shopinfo']['title']+'</a></h3>';
        // generate title1 content
        html_str += '<div id="title1_content" style="margin-left: 15px"><pre>卖家信用: <strong>'+svr_obj['userinfo']['seller_good_num']+'/'+svr_obj['userinfo']['seller_total_num']+' ('+((svr_obj['userinfo']['seller_good_num']/svr_obj['userinfo']['seller_total_num'])*100).toFixed(2)+'%)</strong> <img src="'+SELLER_LEVEL_PIC[svr_obj['userinfo']['seller_level']]+'" />&nbsp;&nbsp;&nbsp;买家信用: <strong>'+svr_obj['userinfo']['buyer_good_num']+'/'+svr_obj['userinfo']['buyer_total_num']+' ('+((svr_obj['userinfo']['buyer_good_num']/svr_obj['userinfo']['buyer_total_num'])*100).toFixed(2)+'%)</strong> <img src="'+BUYER_LEVEL_PIC[svr_obj['userinfo']['buyer_level']]+'" /><br />店铺地址: '+svr_obj['userinfo']['location_city']+'/'+svr_obj['userinfo']['location_state']+'<br />用户注册时间: '+svr_obj['userinfo']['created']+'<br />店铺最后更新: '+svr_obj['shopinfo']['modified']+'</pre></div>';
    }
    return html_str;
}

function generate_issue_list(obj) {
    svr_obj = obj;
    html_str = '';
    if (svr_obj != null) {
        html_str += '<div class="issue-list"><div class="pagination">';
        html_str += '<a href="javascript:load_more_change_event(\''+svr_obj['nick']+'\', '+(svr_obj['offset']-svr_obj['limit'])+', '+svr_obj['limit']+')">‹ Newer</a> | <a href="javascript:load_more_change_event(\''+svr_obj['nick']+'\', '+(svr_obj['offset']+svr_obj['limit'])+', '+svr_obj['limit']+')">Older ›</a>';
        html_str += '</div><table id="queues"><tr align="left" class="first"><th>Summary</th><th>Title</th><th>Time Stamp</th><th>Link</th></tr>';
        for (i=0; i<svr_obj['changeevent'].length; i++) {
            html_str += '<tr name="issue" class="ce_item"><td class="first">['+svr_obj['changeevent'][i]['summary']+']</td>';
            html_str += '<td class="subject"><a>'+svr_obj['changeevent'][i]['title']+'</a></td>';
            html_str += '<td>'+svr_obj['changeevent'][i]['timestamp'].split('.', 1)+'</td>';
            html_str += '<td><a>Link</a></td></tr>';
            
            // issue content
            html_str += '<tr name="issue" class="ce_detail" style="display: none"><td colspan="4"><div>'+svr_obj['changeevent'][i]['content']+'<br />';
            html_str += '<a href="'+ITEM_DETAIL_URL_PREFIX+svr_obj['changeevent'][i]['goods_iid']+'.htm" target="_blank">浏览该商品</a><p />';
            html_str += '<img src="'+svr_obj['changeevent'][i]['goods_pic_path']+'" /><p />';
            html_str += '价格: '+svr_obj['changeevent'][i]['goods_price']+'<br />';
            html_str += '邮费: '+svr_obj['changeevent'][i]['goods_post_fee']+'<br />';
            html_str += '下架时间: '+svr_obj['changeevent'][i]['goods_delist_time']+'</div></td></tr>';
        }
        html_str += '</table></div>';
    }
    return html_str;
}

function generate_change_event(obj) {
    svr_obj = obj;
    html_str = '';
    if(svr_obj != null) {
        // generate title2
        html_str += '<h3><a id="title2" href="javascript:title_toggle(\'title2\', \'title2_content\')" class="toggled-section opentriangle">Change Event</a></h3>';
        html_str += '<div id="title2_content">';
        html_str += generate_issue_list(svr_obj);
        html_str += '</div>';
        return html_str;
    }
}

function generate_update_log(obj) {
    svr_obj = obj;
    html_str = '';
    if (svr_obj != null) {
        html_str += '<h3><a id="title3" href="javascript:title_toggle(\'title3\', \'title3_content\')" class="toggled-section opentriangle">Update Log</a></h3>';
        html_str += '<div id="title3_content"><div style="margin: 15px;">';
        context = {'pre_page':'0', 'current_line_html':''};
        html_page_str = '<em>商品更新</em> <br />';
        html_wangpu_str = '<em>店铺更新</em> <br />';
        for (i=0; i<svr_obj['updatelog'].length; i++) {
            if(svr_obj['updatelog'][i]['log_msg'].indexOf('page') == 0) {
                page_idx = svr_obj['updatelog'][i]['log_msg'].split(' ')[1];
                if (page_idx >= context['pre_page']) {
                    //console.log('new line');
                    html_page_str += context['current_line_html'];
                    html_page_str += svr_obj['updatelog'][i]['update_timestamp'].split('.')[0]+'&nbsp;';
                    context['current_line_html'] = '<br />';
                    //console.log('html='+html_page_str);
                }
                if(svr_obj['updatelog'][i]['log_status']) {
                    context['current_line_html'] = '<span class="update_log_true" title="'+svr_obj['updatelog'][i]['log_msg']+'@'+svr_obj['updatelog'][i]['update_timestamp']+'">&nbsp;'+page_idx+'&nbsp;</span>&nbsp;&nbsp;' + context['current_line_html'];
                } else {
                    context['current_line_html'] = '<span class="update_log_false" title="'+svr_obj['updatelog'][i]['log_msg']+'@'+svr_obj['updatelog'][i]['update_timestamp']+'">&nbsp;'+page_idx+'&nbsp;</span>&nbsp;&nbsp;' + context['current_line_html'];
                }
                context['pre_page'] = page_idx;
                //console.log('i='+i);
                //console.log('line='+context['current_line_html']);
                //console.log('pre_page='+context['pre_page']);
            } else {
                if(svr_obj['updatelog'][i]['log_status']) {
                    html_wangpu_str += svr_obj['updatelog'][i]['update_timestamp'].split('.')[0]+' <span class="update_log_true" title="'+svr_obj['updatelog'][i]['log_msg']+'@'+svr_obj['updatelog'][i]['update_timestamp']+'">&nbsp;W&nbsp;</span>&nbsp;&nbsp;<br />';
                } else {
                    html_wangpu_str += svr_obj['updatelog'][i]['update_timestamp'].split('.')[0]+' <span class="update_log_false" title="'+svr_obj['updatelog'][i]['log_msg']+'@'+svr_obj['updatelog'][i]['update_timestamp']+'">&nbsp;W&nbsp;</span>&nbsp;&nbsp;<br />';
                }
                
            }
        }
        html_page_str += context['current_line_html'];
        html_str += html_page_str;
        html_str += html_wangpu_str;
        html_str += '</div></div>';
        return html_str;
    }
}

function apply_ce_detail_action() {
    $('.ce_item').click(function() {
        detail_obj = $(this).next();
        if(detail_obj.css('display') == 'table-row') {
            detail_obj.css('display', 'none');
            current_display_ce_detail = null;
        } else {
            if(null != current_display_ce_detail) {
                current_display_ce_detail.css('display', 'none');
            }                         
            detail_obj.css('display', 'table-row');
            current_display_ce_detail = detail_obj;
        }
    });
}

function load_main_content(nick) {
    show_tipwindow('Loading...');
    $('#main_content').html('');
    $.ajax({
        url: '/favshop/maincontent',
        type: 'POST',
        data: {'favshopuser':$('#subscription_user').val(), 'nick': nick, 'limit': $('#user_setting_limit').val()},
        error: function(xhr, textStatus) {
            hide_tipwindow();
            show_tiperrwindow('Oops, there are something wrong when server process your request...');
        },
        success: function(data, textStatus) {
            hide_tipwindow();
            //console.log(data);
            svr_obj = JSON.parse(data);
            if(svr_obj == null) {
                show_tiperrwindow('Oops, there are something wrong when server process your request...');
            } else {
                html_str = '';
                html_str += generate_shop_info(svr_obj)
                html_str += generate_change_event(svr_obj);
                html_str += generate_update_log(svr_obj);
                $('#main_content').html(html_str);
                apply_ce_detail_action();
            }
        }
    });
}

function load_more_change_event(nick, offset, limit) {
    show_tipwindow('Loading...');
    $('#title2_content').html('');
    $.ajax({
        url: '/favshop/changeevent',
        data: {'favshopuser': $('#subscription_user').val(), 'nick': nick, 'offset': offset, 'limit': limit},
        type: 'POST',
        error: function(xhr, textStatus) {
            hide_tipwindow();
            show_tiperrwindow('Oops, there are something wrong when server process your request...');
        },
        success: function(data, textStatus) {
            hide_tipwindow();
            svr_obj = JSON.parse(data);
            if(svr_obj == null) {
                show_tiperrwindow('Oops, there are something wrong when server process your request...');
            } else {
                html_str = '';
                html_str += generate_issue_list(svr_obj);
                $('#title2_content').html(html_str);
                apply_ce_detail_action();
            }
        }
    });
}

function load_subscription_side_bar(favshopuser) {
    show_tipwindow('Loading...');
    $.ajax({
        url: '/favshop/sidebar',
        type: 'POST',
        data: {'favshopuser': favshopuser},
        error: function(xhr, textStatus) {
            hide_tipwindow();
            show_tiperrwindow('Oops, there are something wrong when server process your request...');
        },
        success: function(data, textStatus) {
            hide_tipwindow();
            //console.log(data);
            svr_obj = JSON.parse(data)
            if(svr_obj == null) {
                show_tiperrwindow('Oops, there are something wrong when server process your request...');
            } else {
                html_str = '';
                for(i=0; i<svr_obj.length; i++) {
                    html_str += '<ul class="subscription_item"><li class="subscription_title">';
                    html_str += svr_obj[i]['nick'];
                    html_str += '</li><li class="subscription_desc">';
                    html_str += svr_obj[i]['title'];
                    html_str += '</li><li><a href="http://store.taobao.com/shop/view_shop.htm?shop_nick=';
                    html_str += svr_obj[i]['quoted_nick'];
                    html_str += '" target="_blank">去店铺</a>&nbsp;|&nbsp;<a href="javascript:delete_subscription(\'';
                    html_str += svr_obj[i]['nick'];
                    html_str += '\')">删除</a></ul><p />';
                }
                //console.log(html_str);
            }
            $('.issue_detail_sidebar').html(html_str);

            $('li.subscription_title').hover(
                function () {
                    $(this).addClass('subscription_title_highlight');
                }, 
                function () {
                    $(this).removeClass('subscription_title_highlight');
                }
            );
            $('li.subscription_title').click(function() {
                load_main_content($(this).html());
            });
        }
    });
}

$(document).ready(function() {
    load_subscription_side_bar($('#subscription_user').val());
    
    $('#subscription_button').click(function() {
        if($.trim($('#subscription_input').val()) == '') {
            return;
        }
        show_tipwindow('Loading...');
        $.ajax({
            url: '/favshop/subscribe',
            type: 'POST',
            data: {'nick':$.trim($('#subscription_input').val()), 'favshopuser':$('#subscription_user').val()},
            error: function(xhr, textStatus) {
                //console.log(textStatus);
                hide_tipwindow();
                show_tiperrwindow('Oops, there are something wrong when server process your request...');
            },
            success: function(data, textStatus) {
                //console.log(data);
                hide_tipwindow();
                if('ERROR' == data) { // server return OK status
                    show_tiperrwindow('Oops, there are something wrong when server process your request...');
                } else if('FULL' == data) {
                    show_tiperrwindow('Sorry. Currently, you cannot subscribe any more shop.');
                } else if('OK' == data) {
                    ; // do nothing
                } else if('REFRESH' == data) {
                    // refresh side bar
                    load_subscription_side_bar($('#subscription_user').val());
                }
            }
        });
    });
});
